package com.haven123.cloudapp.rabbitmq.demo;

import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * 注解的方式实现创建queue exhange  bindingkey
 */
@Log4j2
@Component
public class AnnotionListener {
    public final static String queue_name="test_con_queue";
    public final static String exchange_name="test_con_exchange";
    public final static String routingKey_name="test_con_routing_key";
    @RabbitListener(bindings =@QueueBinding(value = @Queue(name = queue_name,durable = "false"),
            exchange=@Exchange(name = exchange_name,ignoreDeclarationExceptions = "true",type = ExchangeTypes.DIRECT,durable = "false"),
            key = routingKey_name))
    public void listener(Message message, Channel channel,String hello) throws UnsupportedEncodingException {
        log.info("===========annotionListener==============");
        log.info("message: "+new String(message.getBody(),message.getMessageProperties().getContentEncoding()));
        log.info(new String(message.getBody(), StandardCharsets.UTF_8));
        log.info("hello : "+hello);
        log.info(String.valueOf(message.getBody()));
        // do something

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.error("mq ack error",e);
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException ex) {
                log.error("mq nack error",ex);
            }
        }
    }
}
